import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/store'

// 简化的token时间验证函数
function isTokenExpired(tokenTimeString: string): boolean {
  try {
    const tokenTime = new Date(tokenTimeString)
    const currentTime = new Date()
    const timeDiff = currentTime.getTime() - tokenTime.getTime()
    const oneHourInMs = 60 * 60 * 1000 // 1小时
    return timeDiff >= oneHourInMs
  } catch (error) {
    return true // 解析失败视为过期
  }
}

// 异步组件加载器，添加错误处理
const asyncComponent = (component: () => Promise<any>) => {
  return () => component().catch((error) => {
    console.error('Component loading error:', error)
    // 返回一个简单的错误组件
    return Promise.resolve({
      template: `
        <div style="padding: 40px; text-align: center;">
          <h3>页面加载失败</h3>
          <p>请刷新页面重试</p>
          <button onclick="window.location.reload()">刷新</button>
        </div>
      `
    })
  })
}

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: asyncComponent(() => import('@/views/Login.vue')),
    meta: { 
      requiresAuth: false,
      title: '登录'
    }
  },
  {
    path: '/',
    component: asyncComponent(() => import('@/views/Layout.vue')),
    meta: { 
      requiresAuth: true,
      title: '管理系统'
    },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: asyncComponent(() => import('@/views/Dashboard.vue')),
        meta: { 
          title: '仪表盘',
          icon: 'home'
        }
      },
      {
        path: 'order-management',
        name: 'OrderManagement',
        component: asyncComponent(() => import('@/views/OrderManagement.vue')),
        meta: { 
          title: '订单管理',
          icon: 'document-text'
        }
      },
      {
        path: 'product-management',
        name: 'ProductManagement',
        component: asyncComponent(() => import('@/views/ProductManagement.vue')),
        meta: { 
          title: '商品管理',
          icon: 'cube'
        }
      },
      {
        path: 'user-management',
        name: 'UserManagement',
        component: asyncComponent(() => import('@/views/UserManagement.vue')),
        meta: { 
          title: '用户管理',
          icon: 'people'
        }
      },
      // {
      //   path: 'system-management',
      //   name: 'SystemManagement',
      //   component: asyncComponent(() => import('@/views/SystemManagement.vue')),
      //   meta: { 
      //     title: '系统管理',
      //     icon: 'settings'
      //   }
      // },
      {
        path: 'profile',
        name: 'Profile',
        component: asyncComponent(() => import('@/views/Profile.vue')),
        meta: { 
          title: '个人中心',
          icon: 'person'
        }
      },
      {
        path: 'image-management',
        name: 'ImageManagement',
        component: asyncComponent(() => import('@/views/ImageManagement.vue')),
        meta: { 
          title: '图片管理',
          icon: 'image'
        }
      }
    ]
  },
  // 404 页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: asyncComponent(() => import('@/views/NotFound.vue')),
    meta: {
      title: '页面不存在'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  // 滚动行为
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫 - 简化版本，确保基本功能正常
router.beforeEach((to, from, next) => {
  // 确保在客户端环境下访问store
  if (typeof window !== 'undefined') {
    const authStore = useAuthStore()
    
    console.log('🛡️ Route guard:', {
      to: to.path,
      hasToken: !!authStore.token,
      requiresAuth: to.meta.requiresAuth
    })
    
    // 如果需要认证但没有token，跳转到登录页
    if (to.meta.requiresAuth && !authStore.token) {
      console.log('❌ No token, redirecting to login')
      next('/login')
      return
    }
    
    // 如果已登录访问登录页，跳转到首页
    if (to.path === '/login' && authStore.token) {
      console.log('✅ Already authenticated, redirecting to dashboard')
      next('/')
      return
    }
    
    // 其他情况直接放行
    console.log('✅ Allowing navigation')
    next()
  } else {
    // SSR环境下直接放行
    next()
  }
})

// 路由后置守卫 - 设置页面标题
router.afterEach((to) => {
  if (typeof window !== 'undefined') {
    const title = to.meta.title as string
    document.title = '聚龙科技'
    // if (title) {
    //   document.title = `${title} - DragonsV管理系统`
    // } else {
    //   document.title = 'DragonsV管理系统'
    // }
  }
})

// 路由错误处理
router.onError((error) => {
  //console.error('🚨 Router error:', error)
  // 如果是组件加载错误，重定向到错误页面
  if (error.message.includes('Loading chunk') || error.message.includes('Loading CSS chunk')) {
    //console.log('🔄 Reloading page due to chunk loading error')
    window.location.reload()
  }
})

export default router 